import { IndexDbManager } from './index.db';
import { getNowStr } from './utils';
const MetaDataDBVersion = 2;

type DatabaseEntry = {
  name: string;
  createdAt: string;
  latestReadAt: string;
};

const StoreName = 'model_databases';

/**
 * 数据库管理器
 * 用于管理模型表的"增删"的**记录**
 * 操作metadata库
 */
export class DatabaseManager {
  private db!: IndexDbManager;
  private dbName = 'metadata';
  private _loaded = false;
  get loaded() {
    return this._loaded;
  }
  private set loaded(value: boolean) {
    this._loaded = value;
  }

  async init() {
    const db = new IndexDbManager({
      name: this.dbName,
      version: MetaDataDBVersion,
      stores: [
        {
          name: StoreName,
          indexes: [],
          keyPath: 'name',
          autoIncrement: true,
        },
      ],
    });
    const bool = await db.connect();
    if (!bool) {
      throw new Error('Failed to connect to the database');
    }
    this.db = db;
    console.log('Database initialized:', this.dbName);
    this.loaded = true;
    return this.db;
  }

  async add(name: string) {
    if (!this.db) {
      throw new Error('Database not initialized');
    }
    const createdAt = getNowStr();
    const key = await this.db.add<DatabaseEntry>(StoreName, {
      name,
      createdAt,
      latestReadAt: createdAt,
    });
    return key;
  }

  async addIfNotExists(name: string) {
    if (!this.db) {
      throw new Error('Database not initialized');
    }
    const exists = await this.db.get<DatabaseEntry>(StoreName, name);
    if (!exists) {
      return await this.add(name);
    }
    return null; // 或者返回已存在的记录
  }

  async delete(name: string) {
    if (!this.db) {
      throw new Error('Database not initialized');
    }
    const dbs = await this.db.getAll<DatabaseEntry>(StoreName);
    const dbToRemove = dbs.find((db) => db.name === name);
    if (dbToRemove) {
      await this.db.delete(StoreName, dbToRemove.name);

      return true;
    }
    return false;
  }

  async updateDatabase(name: string) {
    if (!this.db) {
      throw new Error('Database not initialized');
    }
    const dbEntry = await this.db.get<DatabaseEntry>(StoreName, name);
    if (!dbEntry) {
      await this.add(name);
    } else {
      // 更新最新读取时间
      dbEntry.latestReadAt = getNowStr();
      await this.put(dbEntry);
    }
  }

  async put(data: DatabaseEntry) {
    if (!this.db) {
      throw new Error('Database not initialized');
    }
    const dbEntry = await this.db.get<DatabaseEntry>(StoreName, data.name);
    if (dbEntry) {
      // 更新数据库内容
      await this.db.put(StoreName, data);
      return true;
    }
    return false;
  }

  async exists(name: string): Promise<boolean> {
    if (!this.db) {
      throw new Error('Database not initialized');
    }
    const dbs = await this.db.getAll<DatabaseEntry>(StoreName);
    return dbs.some((db) => db.name === name);
  }

  async getAll(): Promise<DatabaseEntry[]> {
    if (!this.db) {
      throw new Error('Database not initialized');
    }
    return await this.db.getAll<DatabaseEntry>(StoreName);
  }
}
